//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON
import WCDBSwift

class UnMuteAllHandler: NoticeHandlerProtocol {
    static let instance = UnMuteAllHandler()

    private init() {
    }

    func handler(_ msg: Message) {
        do {
            let db = SQLiteHelper.getDb()
            try db.run(transaction: { _ in
                if let group = try GroupDao.getGroup(msg.sessionServerId) {
                    group.mute = false
                    try db.update(table: Group.table,
                            on: [Group.CodingKeys.mute],
                            with: group,
                            where: Group.CodingKeys.id == group.id)
                }
            })
            let dic:[String:Any] = ["groupId":msg.sessionServerId,"mute":false]
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNoteChatMsgGroupMute), object: dic)
        } catch {
            print(error)
        }
    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let contact = try ContactDao.getContact(msg.from)
            let groupMember = try GroupDao.getMember(msg.sessionId, userId: msg.from)

            let json = JSON(parseJSON: msg.text ?? "")

            var name = contact?.remarkName ?? groupMember?.nickName ?? contact?.name
            if msg.isMe {
                name = "你"
            }
            return "\(name ?? "管理员" ) 关闭了全体禁言"

        } catch {
            return msg.text
        }
    }
}
